﻿using System;

namespace SqlSugar
{
    public interface ITransactionBase : IDisposable
    {
        void RollbackTran();
        void CommitTran();
    }

    public sealed class TransactionBase : ITransactionBase
    {
        private readonly TransactionData _transactionData;

        internal TransactionBase(TransactionData transactionData)
        {
            _transactionData = transactionData;
        }

        public void RollbackTran()
        {
            if ((_transactionData.Level -= 1) == 0)
            {
                _transactionData.SugarClient.Ado.RollbackTran();
            }
        }

        public void CommitTran()
        {
            if ((_transactionData.Level -= 1) == 0)
            {
                _transactionData.SugarClient.Ado.CommitTran();
            }
        }

        public void Dispose()
        {
            if (_transactionData.Level == 0)
            {
                _transactionData.SugarClient.Ado.Transaction = null;

                _transactionData.SugarClient.Ado.Dispose();

                _transactionData.SugarClient.Dispose();
            }
        }
    }
}
